package com.zenithsun.news.solr.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.syzg.common.config.MyProperties;
import com.zenithsun.news.solr.model.NewsInfo;
import com.zenithsun.news.solr.model.SearchModel;

/**
 * SOLR辅助工具类
 * @author Jiang
 *
 */
public class SolrHelper{
	private static Logger log = LoggerFactory.getLogger(SolrHelper.class);
	//solr 服务
	private static HttpSolrServer solrServer = null;
	//索引库的ID
	private static String indexId = "id";
	//索引库配置
	private static MyProperties procSolr = MyProperties.getInstance("solr.properties");
	public SolrHelper() {
		// TODO Auto-generated constructor stub
		String baseURL = procSolr.getProperty("url") + ":"+
				         procSolr.getProperty("port") + "/"+
				         procSolr.getProperty("app.name");
		indexId = procSolr.getProperty("solr.index.id");
		solrServer = new HttpSolrServer(baseURL);
		log.info("solr:初始化配置完成.....");
	}
	public static SolrHelper getInstance(){
		return new SolrHelper();
	}
	/**
	 * 添加
	 * @param o
	 * @return
	 */
	public boolean insert(NewsInfo o){
		
		try {
			solrServer.addBean(o);
			solrServer.commit();
			log.info("solr: 新增数据完成....");
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("solr: 新增数据错误"+e.getMessage());
		}
		return false;
	}
	/**
	 * 批量添加
	 * @param os
	 * @return
	 */
	public boolean insert(List<NewsInfo> os){
		
		try {
			solrServer.addBeans(os);
			solrServer.commit();
			log.info("solr: 新增数据完成....");
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("solr: 新增数据错误"+e.getMessage());
		}
		return false;
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public boolean delete(String id){
		
		try {
			solrServer.deleteById(id);
			solrServer.commit();
			log.info("solr: 删除数据完成....");
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.error("solr: 删除数据错误"+e.getMessage());
		}
		return false;
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public boolean delete(String[] ids){
		
			List<String> lstIds = new ArrayList<>();
			for (int i = 0; i < ids.length; i++) {
				lstIds.add(ids[i]);
			}
			return delete(lstIds);
	}
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	public boolean delete(List<String> ids){
		try {
			solrServer.deleteById(ids);
			solrServer.commit();
			log.info("solr: 删除数据完成....");
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.error("solr: 删除数据错误"+e.getMessage());
		}
		return false;
	}
	/**
	 * 更新
	 * @param n
	 * @return
	 */
	public boolean update(NewsInfo n){
		try {
			//删除
			solrServer.deleteById(n.getId());
			solrServer.commit();
			//再添加
			solrServer.addBean(n);
			solrServer.commit();
			log.info("solr: 修改数据完成....");
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.error("solr: 修改数据错误"+e.getMessage());
		}
		return false;
	}
	/**
	 * 批量更新
	 * @param ns
	 * @return
	 */
	public boolean update(List<NewsInfo> ns){
		try {
			//先删除
			for (NewsInfo n : ns) {
				solrServer.deleteById(n.getId());
				solrServer.commit();
			}
			//再添加
			solrServer.addBeans(ns);
			solrServer.commit();
			log.info("solr: 修改数据完成....");
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			log.error("solr: 修改数据错误"+e.getMessage());
		}
		return false;
	}
	/**
	 * 查询
	 * @param keyWord 关键字
	 * @return
	 */
	public SolrDocumentList query(String keyWord){
		try {
			SolrQuery params = new SolrQuery();
			params.set("q", "*:"+keyWord);
			QueryResponse response = solrServer.query(params);
			SolrDocumentList results = response.getResults();
			//记录数
			long size = results.getNumFound();
			if(size > 0){
				/*for (SolrDocument doc : results) {
					System.out.println(doc.getFieldValue("id"));
				}*/
				return results;
			}
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 查询
	 * @param keyWord 关键字
	 * @return
	 */
	public SolrDocumentList query(SearchModel sm){
		try {
			SolrQuery params = new SolrQuery();
			//参数  ：前*表示任意字段，后表示任意值
			params.set("q", "*:"+sm.getKeyWord());
			// 设置起始位置与返回结果数
			params.setStart(sm.getStart());
			params.setRows(sm.getLimit());
			// 设置高亮
            if (sm.getHighLight()) {
            	params.setHighlight(true); // 开启高亮组件
            	params.addHighlightField("*");// 高亮字段 （*任意）
            	params.setHighlightSimplePre("<font color=\"red\">");// 高亮标记
            	params.setHighlightSimplePost("</font>");
            	params.setHighlightSnippets(1);// 结果分片数，默认为1
            	params.setHighlightFragsize(1000);// 每个分片的最大长度，默认为100
            }
            //排序
            if(sm.getOrder()!=null&&sm.getOrder().size()>0){
	            for(Entry<String,SolrQuery.ORDER> order:sm.getOrder().entrySet()){
	            	params.addSort(order.getKey(), order.getValue());
	            }
            }
			QueryResponse response = solrServer.query(params);
			//获取结果集
			SolrDocumentList results = response.getResults();
			if(results.getNumFound() > 0){
				/*for (SolrDocument doc : results) {
					System.out.println(doc.getFieldValue("id"));
				}*/
				return results;
			}
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 查询总量
	 * @param keyWord 关键字
	 * @return
	 */
	public long getCount(String keyWord){
		try {
			SolrQuery params = new SolrQuery();
			params.set("q", "*:"+keyWord);
			QueryResponse response = solrServer.query(params);
			SolrDocumentList results = response.getResults();
			//行数
			return results.getNumFound();
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
	
	/**
	 * 根据ID查找
	 * @param id ID
	 * @return
	 */
	public SolrDocument queryById(String id){
		try {
			SolrQuery params = new SolrQuery();
			params.set("q", indexId+":"+id);
			QueryResponse response = solrServer.query(params);
			//获取结果集
			SolrDocumentList results = response.getResults();
			if(results.getNumFound() > 0){
				return results.get(0);
			}
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 检查bean是否存在
	 * @param id ID
	 * @return
	 */
	public boolean beanIsExist(String id){
		try {
			SolrQuery params = new SolrQuery();
			params.set("q", indexId+":"+id);
			QueryResponse response = solrServer.query(params);
			//获取结果集
			SolrDocumentList results = response.getResults();
			if(results.getNumFound() > 0){
				return true;
			}
		} catch (SolrServerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
}
